package com.wlc.collection.myhashmap;

import com.wlc.util.RandomStrUtil;

/**
 * @author 王立朝 wanglichao@champion-credit.com
 * @description 自定义HashCode
 * @date 2021-07-13 10:35
 */
public class MyHashCode {

    /**
     * 生成随机字符串
     *
     * @param length
     * @return
     */
    private static String randomString(int length) {
        String pool = "";
        for (short i = '0'; i <= '9'; i++) {
            pool += (char) i;
        }
        for (short i = 'a'; i <= 'z'; i++) {
            pool += (char) i;
        }
        for (short i = 'A'; i <= 'Z'; i++) {
            pool += (char) i;
        }
        System.out.println("pool = " + pool);
        char cs[] = new char[length];
        for (int i = 0; i < cs.length; i++) {
            double random = Math.random();
            int index = (int) (random * pool.length());
            cs[i] = pool.charAt(index);
        }
        String result = new String(cs);
        return result;
    }

    /**
     * 自定义HashCode
     *
     * @return
     */
    public static int myHashCode(String str) {
        if (null == str) {
            return 0;
        }
        // 自定义hashCode 的规则  字符串 分别相加  ，最后 * 23
        int hashCode = 0;

        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            hashCode += chars[i];
        }
        hashCode = hashCode * 23;
        // 取绝对值
        hashCode = hashCode < 0 ? 0 - hashCode : hashCode;
        // 让hashCode  在0-2000 范围内
        hashCode = hashCode % 2000;
        return hashCode;
    }

    public static void main(String[] args) {

        String s = RandomStrUtil.getRandomString(5);
        int hashCode = myHashCode(s);
        System.out.println("hashCode = " + hashCode);


        int hashCode1 = myHashCode("hello");
        System.out.println("hashCode1 = " + hashCode1);
    }
}
